﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Core.DeviceProtocol;
using Core.Model;
using log4net;

namespace DataServer.View
{
    public delegate void UpdateDataItems(Device dev,List<DataItem> dataItems);
    /// <summary>
    /// DevicePanel.xaml 的交互逻辑
    /// </summary>
    public partial class DevicePanel
    {
        public event UpdateDataItems UpdateDataItems;

        private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private bool _isInit = false;
        public DevicePanel()
        {
            InitializeComponent();
            DataContextChanged += DevicePanel_DataContextChanged;
            this.Loaded += DevicePanel_Loaded;
        }

        private void DevicePanel_Loaded(object sender, RoutedEventArgs e)
        {
            if(_isInit)
                return;
            try
            {
                if (cbbDeviceType.Items.Count == 0)
                {
                    string strPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory +
                                                  Properties.Resources.devprotocolpath);
                    DirectoryInfo driverPath = new DirectoryInfo(strPath);
                    FileInfo[] files = driverPath.GetFiles();
                    cbbProtocol.Items.Clear();
                    for (int i = 0; i < files.Length; i++)
                    {
                        FileVersionInfo info = FileVersionInfo.GetVersionInfo(files[i].FullName);
                        if (info.ProductName != null && info.ProductName.Contains("Protocol"))
                        {
                            cbbProtocol.Items.Add(info.ProductName);
                        }
                    }
                }
               
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            try
            {
                cbbDeviceType.Items.Clear();
                List<DeviceType> deviceTypes = AppManager.DeviceTypeDao.GetEntities();
                if (deviceTypes != null)
                {
                    foreach (DeviceType type in deviceTypes)
                    {
                        cbbDeviceType.Items.Add(type);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            _isInit = true;

        }

        private void DevicePanel_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            Device device = e.NewValue as Device;
            if (device != null && device.DeviceType != null)
            {
                cbbDeviceType.Text = device.DeviceType.Name;
            }
        }

        private void BtnDeviceType_OnClick(object sender, RoutedEventArgs e)
        {
            DeviceTypeView view = new DeviceTypeView();
            view.ShowDialog();
            try
            {
                string text = cbbDeviceType.Text;
                cbbDeviceType.Items.Clear();
                List<DeviceType> deviceTypes = AppManager.DeviceTypeDao.GetEntities();
                if (deviceTypes != null)
                {
                    foreach (DeviceType type in deviceTypes)
                    {
                        cbbDeviceType.Items.Add(type);
                    }
                }
                cbbDeviceType.Text = text;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }

        private void cbbProtocol_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            string selectVal = cbbProtocol.SelectedValue as string;
            if (selectVal == "Dlt645Protocol")
            {
                Device dev = this.DataContext as Device;
                if (dev == null) return;
                List<DataItem> items =  Core.Global.DataAccess.GetDataItems(dev.Id);
                if (dev.Protocol == selectVal && items != null && items.Count > 0) return;
                try
                {
                    string strPath = Core.Global.DataAccess.GetDevProtocolPath();
                    DirectoryInfo driverPath = new DirectoryInfo(strPath);
                    FileInfo[] files = driverPath.GetFiles();

                    for (int i = 0; i < files.Length; i++)
                    {
                        FileVersionInfo info = FileVersionInfo.GetVersionInfo(files[i].FullName);
                        if (info.ProductName != selectVal) continue;
                        if (files[i].Name.Contains(".dll") || files[i].Name.Contains(".DLL"))
                        {
                            string proPath = Path.Combine(strPath, files[i].Name);
                            Assembly asm = Assembly.Load(new AssemblyName() { CodeBase = proPath });
                            foreach (Type extype in asm.GetExportedTypes())
                            {
                                //确定type为类并且继承自(实现)BaseDevProtocol
                                if (extype.IsClass && typeof(BaseDevProtocol).IsAssignableFrom(extype))
                                {
                                    BaseDevProtocol baseDevProtocol = (BaseDevProtocol)Activator.CreateInstance(extype);
                                    List<DataItem> dataItems = baseDevProtocol.GetInitDataItems(dev);
                                    if (dataItems!=null && dataItems.Count>0 && UpdateDataItems != null)
                                    {
                                        UpdateDataItems(dev, dataItems);
                                    }
                                    break;
                                }
                            }
                        }
                    }

                }
                catch 
                {
                }
            }
           
        
        }
    }

   
}
